package com.op.parcel.common.api;

import com.op.parcel.common.enums.ResultEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;

import java.io.Serializable;

/**
 * 结果
 *
 * @author xuan🐽
 */
@Getter
@Setter
@ToString
@ApiModel(description = "返回信息")
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class R<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	@ApiModelProperty(value = "状态码", required = true)
	private int code;
	@ApiModelProperty(value = "是否成功", required = true)
	private boolean success;
	@ApiModelProperty(value = "返回数据")
	private T data;
	@ApiModelProperty(value = "返回消息", required = true)
	private String msg;


	private R(int code, T data, String msg) {
		this.code = code;
		this.data = data;
		this.msg = msg;
		this.success = ResultEnum.SUCCESS.getCode() == code;
	}

	/*返回成功*/
	public static <T> R<T> success() {
		return new R<>(ResultEnum.SUCCESS.getCode(), null, null);
	}

	/*返回成功 数据*/
	public static <T> R<T> success(T data) {
		return new R<>(ResultEnum.SUCCESS.getCode(), data, null);
	}

	/*返回成功 消息*/
	public static <T> R<T> success(String msg) {
		return new R<>(ResultEnum.SUCCESS.getCode(), null, msg);
	}


	/*返回成功 数据 消息*/
	public static <T> R<T> success(T data, String msg) {
		return new R<>(ResultEnum.SUCCESS.getCode(), data, msg);
	}

	/*返回失败状态*/
	public static <T> R<T> error() {
		return new R<>(ResultEnum.ERROR.getCode(), null, null);
	}

	/*返回失败 消息*/
	public static <T> R<T> error(String msg) {
		return new R<>(ResultEnum.ERROR.getCode(), null, msg);
	}

	/*返回失败 内容 消息 */
	public static <T> R<T> error(T data, String msg) {
		return new R<>(ResultEnum.ERROR.getCode(), data, msg);
	}

	/*返回失败 状态码 消息*/
	public static <T> R<T> error(int code, String msg) {
		return new R<>(code, null, msg);
	}


	public static R status(boolean flag) {
		return flag ? success("操作成功") : error("操作失败");
	}


	/*判断是否成功*/
	public boolean isSuccess() {
		return this.success;
	}

	/*判断是否返回了业务数据*/
	public boolean hasData() {
		return (this.data != null);
	}

}
